package ch.mse.android.starbucksfinder.ui;

import java.util.ArrayList;

import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import ch.mse.android.starbucksfinder.MapActivity;
import ch.mse.android.starbucksfinder.StarbucksLocation;

import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.MapView;
import com.google.android.maps.OverlayItem;

public class ItemizedMapOverlay extends ItemizedOverlay<OverlayItem> {
	private ArrayList<OverlayItem> mOverlays = new ArrayList<OverlayItem>();
	private Drawable defaultMarker;
	private Drawable nearestMarker;
	private MapActivity mapActivity;
	
	public ItemizedMapOverlay(Drawable defaultMarker, Drawable neareastMarker, MapActivity mapActivity) {
		super(boundCenterBottom(defaultMarker));
		this.defaultMarker = initMarker(defaultMarker);
		this.nearestMarker = initMarker(neareastMarker);
		this.mapActivity = mapActivity;
	}
	
	private static Drawable initMarker(Drawable marker){
		marker.setBounds(0, 0, marker.getIntrinsicWidth(), marker.getIntrinsicHeight());
		return marker;
	}

	public void addOverlay(OverlayItem overlay) {
	    mOverlays.add(overlay);
	    populate();
	}
	
	public void setNearest(StarbucksLocation nearest){
		for(OverlayItem o : mOverlays){
			if(o instanceof StarbucksOverlayItem){
				StarbucksOverlayItem so = (StarbucksOverlayItem)o;
				if(so.getLocation().equals(nearest)){
					o.setMarker(nearestMarker);
					this.mapActivity.displayBubble(so);
				}else{
					o.setMarker(defaultMarker);
				}
			}
		}
		populate();
	}
	
	@Override
	protected OverlayItem createItem(int i) {
	  return mOverlays.get(i);
	}

	@Override
	public int size() {
		return mOverlays.size();
	}

	@Override
	public void draw(Canvas canvas, MapView mapView, boolean shadow) {
		super.draw(canvas, mapView, false);
	}
	
	@Override
	protected boolean onTap(int index) {
	  StarbucksOverlayItem item = (StarbucksOverlayItem) mOverlays.get(index);
	  this.mapActivity.displayBubble(item);
	  return true;
	}
}
